import {UserOutlined } from '@ant-design/icons';
import {
  Avatar, Radio
} from 'antd';
import { supabase } from '../../../utils';
import { useEffect, useState } from 'react';
import Inputs from '../../../components/Inputs';
import { useStore } from '../../../mobx';
import { getToken } from '../../../utils';
import './index.scss'

export default function Message() {
    const [userData,setuserData]=useState({})  //用户信息
    const {userinformation}=useStore()      
    async function usermessage(){
      const user=JSON.parse(getToken('user'))
      const res=await userinformation.getinformation(user)
      //  console.log(res,'数据');
       setuserData(res.data[0])
    }

  //   上传图片
  async function uploadAvatar(event) {
    try {
      if (!event.target.files || event.target.files.length === 0) {
        throw new Error('You must select an image to upload.')
      }
      const file = event.target.files[0]
      const fileExt = file.name.split('.').pop()
      const fileName = `${Math.random()}.${fileExt}`
      const filePath = `${fileName}`
      // 存储到桶里
      let { error: uploadError } = await supabase.storage
        .from('avatars')
        .upload(filePath, file)
      //移除之前的(替换)
      if(userData.icon&&userData.icon!='https://cc3ihai5g6h4sltf7akg.baseapi.memfiredb.com/storage/v1/object/public/avatars/用户默认头像.png'){  //如果没有头像就不用移除了
        const upImg=userData.icon.split('/')
        const w=upImg[upImg.length-1]
          const { d, e } = await supabase
          .storage
          .from('avatars')
          .remove([w])
      }
      

      //更新必须需存在才能替换，否则报错
      // const { d, e } = await supabase.storage.from('avatars')
      //  .update(w, file, {
      //     cacheControl: '3600',
      //     upsert: false
      //  })
      // console.log(d,e);

      //存储完后在获取
      const { data, error } = supabase.storage
        .from('avatars')
        .getPublicUrl(filePath)
      setuserData({...userData,icon:data.publicURL})  //为了刷新页面，更新状态
      // 把永久地址存到用户icon里
      const { data:test, erro } = await supabase
        .from('user')
        .update({ icon: data.publicURL})
        .match({ username: userData.username })
    } catch (error) {
      alert(error.message)
    } finally {

    }
  }

  function changePassword(e){
    setuserData({...userData,password:e})
  }
  function changeAge(e){
    setuserData({...userData,age:e})
  }
  function changeSex(e){
    setuserData({...userData,sex:e.target.value})
  }
  function changeName(e){
    setuserData({...userData,name:e})
  }
  // 修改基本数据
  async function Submit(){
    const {data,err}=await supabase
    .from('user')
    .update(userData)
    .match({username:userData.username})  //根据账号查找到对应的用户
    // console.log(data,err);
  }
  useEffect(()=>{
    usermessage()
  },[])
  return (
    <div className='Usermessage'>
      <div className='icon'>
        <Avatar src={userData.icon} size={{xs:40,sm:48,md:56,lg:80,xl:96,xxl:116}}  alt='暂无头像' icon={<UserOutlined />}/>
        <input type="file" accept="image/*" className="iconfile" onChange={uploadAvatar}/>
      </div>
      <div className='group'><span>账号</span><Inputs disabled='disabled'  placeholder={userData.username}/></div>
      <div className='group'><span>密码</span><Inputs onchange={changePassword} defaultvalue={userData.password} placeholder='请输入要修改的密码'/></div>
      <div className='group'><span>姓名</span><Inputs onchange={changeName} defaultvalue={userData.name} placeholder='请输入要修改的姓名'/></div>
      <div className='group'><span>年龄</span><Inputs onchange={changeAge} defaultvalue={userData.age} placeholder='请输入要修改的年龄'/></div>
      <div className='group'><span>性别</span>
        <Radio.Group onChange={changeSex} value={userData.sex}>
          <Radio value='男'>男</Radio>
          <Radio value='妖'>妖</Radio>
          <Radio value='女'>女</Radio>
        </Radio.Group>
      </div>
      <div className="btn btn__secondary" onClick={Submit}><p>保存</p></div>

    </div>
  )
}